// pages/comment/comment.js
var util = require('../../utils/util.js')
var config = require('../../config/config.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    id: 0,
    score: 0,
    comment: '',
    foodId: 0,

    showAddFoodDesc: true,
    grids: [],
    commentImgUrls: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let food_id = options.food_id
    let comment_id = options.comment_id
    this.setData({
      id: comment_id,
      foodId: food_id
    })

    this.getWxUserInfo()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

  getWxUserInfo: function () {
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
      })
    } else if (wx.canIUse('button.open-type.getUserInfo')) {
      // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
      // 所以此处加入 callback 以防止这种情况
      app.userInfoReadyCallback = res => {
        this.setData({
          userInfo: res.userInfo,
        })
      }
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          this.setData({
            userInfo: res.userInfo,
          })
        }
      })
    }
  },

  clickStar: function (event) {
    let score = event.currentTarget.dataset.score
    this.setData({
      score: score
    })
  },

  bindInputComment: function (e) {
    this.setData({
      comment: e.detail.value
    })
  },

  clickUploadComment: function () {
    if (this.data.score === 0) {
      this.showTipModal("不可以给0分呦，太残忍了！")
      return
    }
    if (this.data.comment.length < 15) {
      this.showTipModal("评价不能少于15个字哦！")
      return
    }

    this.uploadCommentImgs()
  },

  uploadComment: function () {
    let that = this
    wx.request({
      url: `${config.requestBaseUrl}/Comment/UploadComment`,
      method: 'POST',
      data: {
        id: this.data.id,
        openid: wx.getStorageSync('openid'),
        food_id: this.data.foodId,
        comment_text: this.data.comment,
        score: this.data.score,
        avatar_url: this.data.userInfo.avatarUrl,
        nickname: this.data.userInfo.nickName,
        comment_img1: this.data.commentImgUrls[0] ? this.data.commentImgUrls[0] : '',
        comment_img2: this.data.commentImgUrls[1] ? this.data.commentImgUrls[1] : '',
        comment_img3: this.data.commentImgUrls[2] ? this.data.commentImgUrls[2] : '',
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.data.code == 1) {
          wx.redirectTo({
            url: `../food/food?food_id=${that.data.foodId}`,
          })
        } else {
          that.showTipModal('上传错误')
          console.log(res.data)
        }
      }
    })
  },

  showTipModal: function (tipInfo) {
    wx.showModal({
      content: tipInfo,
      showCancel: false,
      success: function (res) {
        if (res.confirm) {
          // console.log('用户点击确定')
        }
      }
    });
  },

  clickDeleteDescImg: function (event) {
    let index = event.currentTarget.dataset.index
    let imgGrids = this.data.grids
    imgGrids.splice(index, 1)
    this.setData({
      grids: imgGrids,
    })
    if (this.data.grids.length < 3) {
      this.setData({
        showAddFoodDesc: true
      })
    }
  },

  chooseFoodDescImg: function () {
    let that = this
    let imgGrids = this.data.grids
    if (imgGrids.length >= 3) {
      return
    }
    util.chooseImage(function (res) {
      let needImgNum = 3 - imgGrids.length
      let imgNum = needImgNum >= res.tempFilePaths.length ? res.tempFilePaths.length : needImgNum
      for (let i = 0; i < imgNum; i++) {
        imgGrids.push(res.tempFilePaths[i])
      }
      that.setData({
        grids: imgGrids
      })
      if (that.data.grids.length >= 3) {
        that.setData({
          showAddFoodDesc: false
        })
      }
    })
  },

  uploadCommentImgs: function () {
    let that = this
    let imgGrids = this.data.grids
    // let imgUrls = this.data.foodDescImgUrls
    let urlGrids = []
    // console.log(imgGrids)
    for (let i = 0, len = imgGrids.length; i < len; i++) {
      // if (imgGrids[i] == imgUrls[i]) {
      //   urlGrids.push(imgUrls[i])
      //   if (urlGrids.length == len) {
      //     that.setData({
      //       foodDescImgUrls: urlGrids
      //     })
      //     that.uploadFoodInfoToServer()
      //   }
      //   continue
      // }
      util.wxUploadFile(imgGrids[i],
        successRes => {
          urlGrids.push(successRes.fileUrl)
          if (urlGrids.length == len) {
            that.setData({
              commentImgUrls: urlGrids
            })
            that.uploadComment()
            console.log(that.data.commentImgUrls)
          }
        },
        failRes => {
          console.log(failRes)
        })
    }
    if (imgGrids.length == 0) {
      that.uploadComment()
      // wx.hideLoading()
    }
  }


})